package com.xo.xodemo.controller.processProofbargain;


import com.xo.xodemo.mapper.db1.DepartmentMapper;
import com.xo.xodemo.mapper.db1.ProofBargainMapper;
import com.xo.xodemo.model.Department;
import com.xo.xodemo.model.ProofBargain;
import com.xo.xodemo.model.ProofBargainForStatistics;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xo.xodemo.common.Result;

import java.util.*;

@Controller
@RequestMapping("/proofbargain")
public class ProcessProofbargainController {
    @Autowired
    ProofBargainMapper proofBargainMapper;
    @Autowired
    DepartmentMapper departmentMapper;

    //销售统计(饼图）
    @RequestMapping("/salesStatisticsForPieChart")
    @ResponseBody
    public List<List<Object>> salesStatisticsforpieChart(@Param("datetime") String datetime, @Param("month") String month,@Param("year") String year){
        List<List<Object>> RequestList = new ArrayList<>();//存放最终结果
        //1.查询有多少个部门
        List<Department> departmentList =  departmentMapper.findAllXS();
        //2.查询proofBargain表的信息
        List<ProofBargainForStatistics> proofBargainList = proofBargainMapper.selectPaymentAmount();
        //3.遍历部门
        for (int i=0;i<departmentList.size();i++){
            List RequestListForOne = new ArrayList();// 存放每个部门的销售额
            //记录部门总金额
            Double paymentAmount = Double.valueOf(0);
            //记录部门成交单数量
            Integer paymentNumbers = 0;
            //4.遍历成交单表，将每个部门的销售金额加起来
            for (int j=0;j<proofBargainList.size();j++){
                //5.筛选同一个部门的成交单
                if (departmentList.get(i).getDepartmentId() == proofBargainList.get(j).getDepartmentId()){
                    //6.对时间数据处理
                    // 6.1当时间参数是：“日”
                    if(datetime != null && !datetime.equals("")) {
                        //6.1.1去掉datetime参数中间的“-”,并转成Ingteger类型
                        Integer newdatetime =  Integer.valueOf(datetime.replace("-",""));
                        //6.1.2将成交单中的日期按“ / ”拆分成字符串，只要最后一个日期
                        String[] transFerDates = proofBargainList.get(j).getTransferDate().split(" / ");
                        String transFerDate = transFerDates[transFerDates.length-1];
                        //补:去掉最后一个日期中所有的空格
                        transFerDate = transFerDate.replace(" ", "");
                        //6.1.3将成交单中的收款金额取出来
                        String TheOnePaymentAmount = proofBargainList.get(j).getPaymentAmount();
                        //6.1.4将日期数组中的元素的“-”去掉，并且转换成Integer类型
                        Integer newTransFerDate = Integer.valueOf(transFerDate.replace("-",""));
                        //6.1.5将每条数据的日期跟时间参数“日”，做筛选
                        if (newdatetime.equals(newTransFerDate)){
                            //6.1.6将金额数组中的金额转换成Integer类型
                            Double pA = Double.valueOf(TheOnePaymentAmount);
                            //6.1.7将该部门下，符合时间参数条件的转账金额累加
                            paymentAmount += pA;
                            paymentNumbers += 1;
                        }
                    }
                    //6.2当时间参数是：“月”
                    else if (month != null && !month.equals("")){
                        //6.2.1去掉month参数中间的“-”,然后转成Integer类型
                        Integer newmonth = Integer.valueOf(month.replace("-",""));
                        //6.2.2将成交单中的日期按“ / ”拆分成字符数组，并且遍历它,只要最后一个日期
                        String[] transFerDates = proofBargainList.get(j).getTransferDate().split(" / ");
                        String transFerDate = transFerDates[transFerDates.length-1];
                        //补:去掉最后一个日期中所有的空格
                        transFerDate = transFerDate.replace(" ", "");
                        //6.2.3将成交单中的收款金额取出来
                        String TheOnePaymentAmount = proofBargainList.get(j).getPaymentAmount();
                        //6.2.4将日期的“-”去掉
                        String tfDate = transFerDate.replace("-","");
                        //6.2.5将tfDate截取，截取年月的位置,并转换成Integer类型
                        Integer newTransFerDate = Integer.valueOf(tfDate.substring(0,6));
                        //6.2.6将日期元素跟时间参数“月”，做筛选
                        if (newmonth.equals(newTransFerDate)){
                            //6.2.7将金额数组中的金额转换成Integer类型
                            Double pA = Double.valueOf(TheOnePaymentAmount);
                            //6.2.8将该部门下，符合时间参数条件的转账金额累加
                            paymentAmount += pA;
                            paymentNumbers += 1;
                        }
                    }
                    //6.3当没有参数或者参数是“年”
                    else {
                        //6.3.1当时间参数是空的获取当前年份
                        if (year == null || year.equals("")){
                            //获取当前年份
                            Calendar calendar = Calendar.getInstance();
                            year = String.valueOf(calendar.get(Calendar.YEAR));
                        }
                        //6.3.2year参数转成Integer类型
                        Integer newyear = Integer.valueOf(year);
                        //6.3.3将成交单中的日期按“ / ”拆分成字符数组，并且遍历它,只要最后一个日期
                        String[] transFerDates = proofBargainList.get(j).getTransferDate().split(" / ");
                        String transFerDate = transFerDates[transFerDates.length-1];
                        //补:去掉最后一个日期中所有的空格
                        transFerDate = transFerDate.replace(" ", "");
                        //6.3.4将成交单中的收款金额取出来
                        String TheOnePaymentAmount = proofBargainList.get(j).getPaymentAmount();
                        //6.3.5将日期的“-”去掉
                        String tfDate = transFerDate.replace("-","");
                        //6.3.6将tfDate截取，截取年月的位置,并转换成Integer类型
                        Integer newTransFerDate = Integer.valueOf(tfDate.substring(0,4));
                        //6.3.7将日期元素跟时间参数“年”，做筛选
                        if (newyear.equals(newTransFerDate)){
                            //6.3.8将金额数组中的金额转换成Integer类型
                            Double pA = Double.valueOf(TheOnePaymentAmount);
                            //6.3.9将该部门下，符合时间参数条件的转账金额累加
                            paymentAmount += pA;
                            paymentNumbers += 1;

                        }
                    }
                }
            }
            RequestListForOne.add(departmentList.get(i).getDepartmentName());//7.把每个部门名称放到集合
            RequestListForOne.add(Math.round(paymentAmount * 100.0) / 100.0);//8.把每个部门对应计算好的销售总额存放到集合
            RequestListForOne.add(paymentNumbers);//9.把每个部门对应计算好的成交单数量放到集合
            RequestList.add(RequestListForOne);//10.把map放入list集合中
        }
        return RequestList;
    }

    //销售统计折线图
    @RequestMapping("/salesStatisticsForLineChart")
    @ResponseBody
    public Map<String,List> salesStatisticsForlineChart(@Param("month") String month, @Param("year") String year){
        List<String> lineChartXdata = new ArrayList<>();
        String[] monthNums = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};//月份;
        //一.折线图数据处理
        Map<String,List> resultMap = new HashMap<>();//最终返回值
        //1.查询有多少个部门
        List<Department> departmentList =  departmentMapper.findAllXS();
        //2.查询proofBargain表的信息
        List<ProofBargainForStatistics> proofBargainList = proofBargainMapper.selectPaymentAmount();
        //3.如果month参数不存在
        if (month == null || month.equals("")){
            //4.如果year参数也不存在则获取当前年份
            if (year == null || year.equals("")){
                Calendar calendar = Calendar.getInstance();
                //4.1获取当前年份
                year = String.valueOf(calendar.get(Calendar.YEAR));
            }
            lineChartXdata.addAll(Arrays.asList(monthNums));//折线图x轴信息
            //5.遍历部门
            for (int i=0;i<departmentList.size();i++){
                List everyMonthPaymentAmount = new ArrayList();//存放每个部门-每个月的销售额
                List everyDayPaymentNumbers = new ArrayList();//存放每个部门-每天的成交单数
                //6.配合当前年份，拼接上12个月，组成新的字符并遍历
                for (String monthNum:monthNums){
                    Double paymentAmount = Double.valueOf(0); //记录部门总金额
                    Integer paymentNumbers = 0; //记录部门成交单数量
                    //7.将当前年份跟月份数组中的每个元素组成新的字符
                    Integer currentYearMonth = Integer.valueOf(year.concat(monthNum));
                    //8.遍历成交单表，将每个部门的销售金额加起来
                    for (int j=0;j<proofBargainList.size();j++) {
                        //9.筛选同一个部门的成交单
                        if (departmentList.get(i).getDepartmentId() == proofBargainList.get(j).getDepartmentId()) {
                            //10.将成交单中的日期按“ / ”拆分成字符数组，并且遍历它,只要最后一个日期
                            String[] transFerDates = proofBargainList.get(j).getTransferDate().split(" / ");
                            String transFerDate = transFerDates[transFerDates.length-1];
                            //补:去掉最后一个日期中所有的空格
                            transFerDate = transFerDate.replace(" ", "");
                            //11.将成交单中的收款金额取出来
                            String TheOnePaymentAmount = proofBargainList.get(j).getPaymentAmount();
                            //12.将日期的“-”去掉
                            String tfDate = transFerDate.replace("-","");
                            //13.将tfDate截取，截取年月的位置,并转换成Integer类型
                            Integer newTransFerDate = Integer.valueOf(tfDate.substring(0,6));
                            //14.将数组中的日期元素跟时间参数做筛选
                            if (currentYearMonth.equals(newTransFerDate)){
                                //15.将金额数组中的金额转换成Integer类型
                                Double pA = Double.valueOf(TheOnePaymentAmount);
                                //16.将该部门下，符合时间参数条件的转账金额累加
                                paymentAmount += pA;
                                paymentNumbers += 1;
                            }
                        }
                    }
                    //17.将一个部门一个月的销售额存起来
                    everyMonthPaymentAmount.add(Math.round(paymentAmount * 100.0) / 100.0);
                    //把一个部门这一天的成交单数量存起来
                    everyDayPaymentNumbers.add(paymentNumbers);
                }
                //18.将一个部门的部门名称跟该部门一年中每个月的销售额存起来
                resultMap.put(departmentList.get(i).getDepartmentName(),everyMonthPaymentAmount);
                //把一个部门的“部门的名称+PaymentNumbers”跟这一个月中每天的成交单数量保存起来
                resultMap.put(departmentList.get(i).getDepartmentName()+"PaymentNumbers",everyDayPaymentNumbers);
            }
        }
        else {
            //4.把参数拆分成年和月
            String[] parameterYearAndMonth =  month.split("-");
            int parameterYear = Integer.parseInt(parameterYearAndMonth[0]);
            int parameterMonth = Integer.parseInt(parameterYearAndMonth[1]);
            //5.调用方法获取参数对应月份的天数
            int theMonthForDays = getMonthDays(parameterYear,parameterMonth);
            List<String> dayNumsList = new ArrayList();//存放参数月的"日"的集合
            //6.得到该月份对应的“日”
            String[] dayNums = {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25",
                    "26","27","28","29","30","31","32","33"};//日
            for (int i=0;i<theMonthForDays;i++){
                dayNumsList.add(dayNums[i]);
            }
            lineChartXdata.addAll(dayNumsList);
            //4.1将参数中的“-”去掉为后面拼接使用
            String nweMonth = month.replace("-","");
            //7.遍历部门
            for (int i=0;i<departmentList.size();i++){
                List everyDayPaymentAmount = new ArrayList();//存放每个部门-每天的销售额
                List everyDayPaymentNumbers = new ArrayList();//存放每个部门-每天的成交单数
                //8.遍历“日”集合，拼接上参数形成 MMMM-DD-SS的形式
                for (String dayNum:dayNumsList){
                    Double paymentAmount = Double.valueOf(0); //记录部门总金额
                    Integer paymentNumbers = 0; //记录部门成交单数量
                    //9.将参数month（MMMM-DD）跟“日”拼接，形成 MMMM-DD-SS的形式
                    Integer dateMonthAndDay = Integer.valueOf(nweMonth.concat(dayNum));
                    //10.遍历成交单表，将每个部门的销售金额加起来
                    for (int j=0;j<proofBargainList.size();j++) {
                        //11.筛选同一个部门的成交单
                        if (departmentList.get(i).getDepartmentId() == proofBargainList.get(j).getDepartmentId()) {
                            //12.将成交单中的日期按“ / ”拆分成字符数组，并且遍历它,只要最后一个日期
                            String[] transFerDates = proofBargainList.get(j).getTransferDate().split(" / ");
                            String transFerDate = transFerDates[transFerDates.length-1];
                            //补:去掉最后一个日期中所有的空格
                            transFerDate = transFerDate.replace(" ", "");
                            //13.将成交单中的收款金额取出来
                            String TheOnePaymentAmount = proofBargainList.get(j).getPaymentAmount();
                            //14.将日期的“-”去掉
                            String tfDate = transFerDate.replace("-","");
                            //15.将日期转换成Integer类型
                            Integer newTransFerDate = Integer.valueOf(tfDate);
                            //16.将数组中的日期元素跟时间参数做筛选
                            if (dateMonthAndDay.equals(newTransFerDate)){
                                //17.将金额数组中的金额转换成Integer类型
                                Double pA = Double.valueOf(TheOnePaymentAmount);
                                //18.将该部门下，符合时间参数条件的转账金额累加
                                paymentAmount += pA;
                                paymentNumbers += 1;
                            }
                        }
                    }
                    //19.把一个部门这一天的销售金额存起来
                    everyDayPaymentAmount.add(Math.round(paymentAmount * 100.0) / 100.0);
                    //把一个部门这一天的成交单数量存起来
                    everyDayPaymentNumbers.add(paymentNumbers);
                }
                //20.把一个部门的“部门的名称”跟这一个月中每天的销售金额保存起来
                resultMap.put(departmentList.get(i).getDepartmentName(),everyDayPaymentAmount);
                //把一个部门的“部门的名称+PaymentNumbers”跟这一个月中每天的成交单数量保存起来
                resultMap.put(departmentList.get(i).getDepartmentName()+"PaymentNumbers",everyDayPaymentNumbers);
            }
        }
        resultMap.put("lineChartXdata",lineChartXdata);
        return resultMap;
    }

    /**
     * 传入时间 获得天数 如果要得到其他月份的天数 设置对象的月份以及年份即可
     * */
    public static int getMonthDays(int year , int month) {
        Calendar a = Calendar.getInstance();//获取当前时间
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);// Calendar月份是以0开始的 所以要-1
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int day = a.get(Calendar.DATE);
        return day;
    }


}